package com.chaoxi.picturebackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoxi.picturebackend.annotation.AuthCheck;
import com.chaoxi.picturebackend.common.BaseResponse;
import com.chaoxi.picturebackend.common.DeleteBatchRequest;
import com.chaoxi.picturebackend.common.DeleteRequest;
import com.chaoxi.picturebackend.common.ResultUtils;
import com.chaoxi.picturebackend.constant.UserConstant;
import com.chaoxi.picturebackend.exception.ErrorCode;
import com.chaoxi.picturebackend.exception.ThrowUtils;
import com.chaoxi.picturebackend.model.dto.tag.TagAddRequest;
import com.chaoxi.picturebackend.model.dto.tag.TagEditRequest;
import com.chaoxi.picturebackend.model.dto.tag.TagQueryRequest;
import com.chaoxi.picturebackend.model.dto.tag.TagUpdateRequest;

import com.chaoxi.picturebackend.model.entity.PictureTag;
import com.chaoxi.picturebackend.model.entity.User;
import com.chaoxi.picturebackend.service.PictureTagService;
import com.chaoxi.picturebackend.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/tag")
@RequiredArgsConstructor
public class PictureTagController {

    @Resource
    private PictureTagService pictureTagService;

    @Resource
    private UserService userService;

    /**
     * 创建标签
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("创建标签")
    public BaseResponse<Long> addTag(@RequestBody TagAddRequest tagAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(tagAddRequest == null, ErrorCode.PARAMS_ERROR);

        PictureTag pictureTag = new PictureTag();
        BeanUtils.copyProperties(tagAddRequest, pictureTag);

        // 设置创建信息
        User loginUser = userService.getLoginUser(request);
        pictureTag.setCreateTime(new Date());
        pictureTag.setUpdateTime(new Date());
        pictureTag.setCreateUser(loginUser.getId());
        pictureTag.setIsDelete(0);
        // 设置默认层级
        if (pictureTag.getParentId() != null && pictureTag.getParentId() > 0) {
            // 如果有父标签，则层级为父标签层级+1
            PictureTag parentTag = pictureTagService.getById(pictureTag.getParentId());
            if (parentTag != null) {
                pictureTag.setLevel(parentTag.getLevel() + 1);
                // 构建路径
                pictureTag.setPath(parentTag.getPath() + "," + pictureTag.getId());
            }
        } else {
            // 顶级标签
            pictureTag.setParentId(null);
            pictureTag.setLevel(0);
        }

        // 数据校验
        validTag(pictureTag);

        // 保存到数据库
        boolean result = pictureTagService.save(pictureTag);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        
        // 清除标签缓存
        pictureTagService.clearTagCache();

        return ResultUtils.success(pictureTag.getId());
    }

    /**
     * 删除标签
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("删除标签")
    public BaseResponse<Boolean> deleteTag(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_ERROR);
        long id = deleteRequest.getId();
        // 判断是否存在
        PictureTag oldTag = pictureTagService.getById(id);
        ThrowUtils.throwIf(oldTag == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = pictureTagService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        
        // 清除标签缓存
        pictureTagService.clearTagCache();
        
        return ResultUtils.success(true);
    }

    /**
     * 批量删除标签
     */
    @PostMapping("/delete/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("批量删除标签")
    public BaseResponse<Boolean> deleteTagBatch(@RequestBody DeleteBatchRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() == null || deleteRequest.getId().isEmpty(),
                ErrorCode.PARAMS_ERROR, "请选择要删除的标签");

        List<Long> ids = deleteRequest.getId();

        // 检查所有标签是否存在
        for (Long id : ids) {
            PictureTag oldTag = pictureTagService.getById(id);
            ThrowUtils.throwIf(oldTag == null, ErrorCode.NOT_FOUND_ERROR, "标签不存在: " + id);
        }

        // 执行批量删除
        boolean result = pictureTagService.removeByIds(ids);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        
        // 清除标签缓存
        pictureTagService.clearTagCache();

        return ResultUtils.success(true);
    }

    /**
     * 更新标签（管理员）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("更新标签（管理员）")
    public BaseResponse<Boolean> updateTag(@RequestBody TagUpdateRequest tagUpdateRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(tagUpdateRequest == null || tagUpdateRequest.getId() == null, ErrorCode.PARAMS_ERROR);

        // 判断是否存在
        long id = tagUpdateRequest.getId();
        PictureTag oldTag = pictureTagService.getById(id);
        ThrowUtils.throwIf(oldTag == null, ErrorCode.NOT_FOUND_ERROR);

        // 更新对象
        PictureTag pictureTag = new PictureTag();
        BeanUtils.copyProperties(tagUpdateRequest, pictureTag);
        pictureTag.setUpdateTime(new Date());
        
        // 处理层级关系
        if (pictureTag.getParentId() != null && pictureTag.getParentId() > 0) {
            // 如果有父标签，则层级为父标签层级+1
            PictureTag parentTag = pictureTagService.getById(pictureTag.getParentId());
            if (parentTag != null) {
                pictureTag.setLevel(parentTag.getLevel() + 1);
            }
        } else {
            // 顶级标签
            pictureTag.setParentId(null);
            pictureTag.setLevel(0);
        }

        // 数据校验
        validTag(pictureTag);

        // 操作数据库
        boolean result = pictureTagService.updateById(pictureTag);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        
        // 清除标签缓存
        pictureTagService.clearTagCache();

        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取标签
     */
    @GetMapping("/get")
    @ApiOperation("根据 id 获取标签")
    public BaseResponse<PictureTag> getTagById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);

        PictureTag pictureTag = pictureTagService.getById(id);
        ThrowUtils.throwIf(pictureTag == null, ErrorCode.NOT_FOUND_ERROR);
        ThrowUtils.throwIf(pictureTag.getIsDelete() == 1, ErrorCode.NOT_FOUND_ERROR, "标签已被删除");

        return ResultUtils.success(pictureTag);
    }

    /**
     * 分页获取标签列表
     */
    @PostMapping("/list/page")
    @ApiOperation("分页获取标签列表")
    public BaseResponse<Page<PictureTag>> listTagByPage(@RequestBody TagQueryRequest tagQueryRequest) {
        long current = tagQueryRequest.getCurrent();
        long size = tagQueryRequest.getPageSize();

        // 查询数据库
        QueryWrapper<PictureTag> queryWrapper = getQueryWrapper(tagQueryRequest);
        Page<PictureTag> tagPage = pictureTagService.page(new Page<>(current, size), queryWrapper);

        return ResultUtils.success(tagPage);
    }

    /**
     * 获取所有标签列表（不分页）
     */
    @PostMapping("/list")
    @ApiOperation("获取所有标签列表")
    public BaseResponse<List<PictureTag>> listTag() {
        List<PictureTag> tagList = pictureTagService.list();
        return ResultUtils.success(tagList);
    }

    /**
     * 标签数据校验
     */
    private void validTag(PictureTag pictureTag) {
        ThrowUtils.throwIf(pictureTag == null, ErrorCode.PARAMS_ERROR);
        String tagName = pictureTag.getTagName();
        ThrowUtils.throwIf(tagName == null || tagName.trim().isEmpty(), ErrorCode.PARAMS_ERROR, "标签名称不能为空");
        ThrowUtils.throwIf(tagName.length() > 50, ErrorCode.PARAMS_ERROR, "标签名称过长");
    }

    /**
     * 获取查询条件
     */
    private QueryWrapper<PictureTag> getQueryWrapper(TagQueryRequest tagQueryRequest) {
        QueryWrapper<PictureTag> queryWrapper = new QueryWrapper<>();
        if (tagQueryRequest == null) {
            return queryWrapper;
        }
        Long id = tagQueryRequest.getId();
        String tagName = tagQueryRequest.getTagName();
        String description = tagQueryRequest.getDescription();
        Long parentId = tagQueryRequest.getParentId();
        Integer level = tagQueryRequest.getLevel();
        String sortField = tagQueryRequest.getSortField();
        String sortOrder = tagQueryRequest.getSortOrder();

        // 构建查询条件
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.like(tagName != null, "tagName", tagName);
        queryWrapper.like(description != null, "description", description);
        queryWrapper.eq(parentId != null, "parentId", parentId);
        queryWrapper.eq(level != null, "level", level);

        // 排序
        if (sortField != null && sortOrder != null) {
            queryWrapper.orderBy(true, "asc".equals(sortOrder), sortField);
        } else {
            queryWrapper.orderByDesc("createTime");
        }

        return queryWrapper;
    }


    /**
     * 批量插入示例分类数据
     */
    @PostMapping("/add/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("批量插入标签数据")
    public BaseResponse<Boolean> addExampleCategoriesBatch(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Date now = new Date();

        // 定义示例分类数据
        List<String> exampleCategories = List.of(
                "城市", "摩天大楼", "街道", "道路", "桥梁", "城堡", "教堂", "寺庙", "医院", "学校",
                "地标", "食物", "咖啡", "手机", "电脑", "汽车", "飞机", "时钟", "音乐", "礼物",
                "黑白", "单色", "彩色", "鲜艳", "柔和", "粉彩", "暗色调", "亮色调", "复古色", "莫兰迪色",
                "温馨", "浪漫", "宁静", "孤独", "神秘", "恐怖", "史诗感", "充满希望", "怀旧", "梦幻", "奢华",
                "简约", "极简主义", "抽象", "油画风", "水彩风", "卡通", "插画", "像素风", "赛博朋克", "复古", "未来感",
                "模糊", "光斑", "长曝光", "双重曝光", "漏光", "胶片颗粒", "HDR",
                "社交媒体", "微信", "微博", "抖音", "小红书", "Instagram", "Facebook", "博客", "网站", "演示文稿"
        );

        // 转换为实体对象
        List<PictureTag> tags = exampleCategories.stream().map(categoryName -> {
            PictureTag tag = new PictureTag();
            tag.setTagName(categoryName);
            tag.setDescription(categoryName);
            tag.setCreateTime(now);
            tag.setUpdateTime(now);
            tag.setCreateUser(loginUser.getId());
            tag.setIsDelete(0);
            // 默认都是顶级标签
            tag.setParentId(null);
            tag.setLevel(0);
            return tag;
        }).collect(java.util.stream.Collectors.toList());

        // 批量保存到数据库
        boolean result = pictureTagService.saveBatch(tags);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "批量插入数据失败");

        return ResultUtils.success(true);
    }

}